package org.example.lotterysystem.service.postwinning.impl;

import org.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import org.example.lotterysystem.common.exception.ServiceException;
import org.example.lotterysystem.dao.dataobject.WinningRecordDO;
import org.example.lotterysystem.service.activitystatus.impl.ActivityStatusManagerImpl;
import org.example.lotterysystem.service.activitystatus.operater.AbstractActivityOperator;
import org.example.lotterysystem.service.postwinning.PostWinningManager;
import org.example.lotterysystem.service.postwinning.operater.AbstractPostWinning;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Component
public class PostWinningManagerImpl implements PostWinningManager {

    private static final Logger logger = LoggerFactory.getLogger(ActivityStatusManagerImpl.class);

    @Autowired
    private final Map<String, AbstractPostWinning> operatorMap = new HashMap<>();

    @Override
    public Integer send(List<WinningRecordDO> winningRecordDOList) {
        if (CollectionUtils.isEmpty(operatorMap)) {
            logger.warn("operatorMap 为空！");
            return 2;
        }
        Map<String, AbstractPostWinning> currMap = new HashMap<>(operatorMap);
        Boolean update = false;
        // 先处理：人员、奖品
        update = processPost(winningRecordDOList, currMap, 1);
        if(update){
            return 1;
        }
        return 2;
    }

    private Boolean processPost(List<WinningRecordDO> winningRecordDOList, Map<String, AbstractPostWinning> currMap, int sequence) {
        Boolean update = false;
        // 遍历currMap
        Iterator<Map.Entry<String, AbstractPostWinning>> iterator = currMap.entrySet().iterator();
        while (iterator.hasNext()) {
            AbstractPostWinning operator = iterator.next().getValue();
            // Operator 是否需要转换
            if (operator.sequence() != sequence) {
                continue;
            }
            // 需要转换：转换
            operator.execute(winningRecordDOList);
            // currMap 删除当前 Operator
            iterator.remove();
            update = true;
        }
        // 返回
        return update;
    }

}
